//
//  OverlaySheet.swift
//  PokeMaster
//
//  Created by 李腾芳 on 2022/1/16.
//  Copyright © 2022 OneV's Den. All rights reserved.
//

import SwiftUI

struct Blur: ViewModifier {
    var active: Bool
    func body(content: Content) -> some View {
        return content.offset(y: active ?  UIScreen.main.bounds.height : 0)
    }
    
    
}
extension AnyTransition {
    static var blur: AnyTransition {
        .modifier(active: Blur(active: true), identity: Blur(active: false))
    }
}

struct OverlaySheet<Content: View>: View {
    let isPresented: Binding<Bool>
    let content: () -> Content
    @GestureState private var translation = CGPoint.zero
    
    init(isPresented: Binding<Bool>, @ViewBuilder content: @escaping () -> Content) {
        self.isPresented = isPresented
        self.content = content
    }
    var body: some View {
        if isPresented.wrappedValue {
        VStack(spacing: 0) {
            // Spacer()
            Rectangle()
                .fill(Color.gray)
                .opacity(0.5)
            //                    .gesture(
            //                        DragGesture()
            //                    )
           
            content()
        }
        .offset(y: max(0, translation.y))
        .edgesIgnoringSafeArea(.bottom)
        .gesture(panelDraggingGesture)
        .transition(AnyTransition.blur)
        .animation(animation)
        }
    }
  //  let animation: Animation = .interpolatingSpring(stiffness: 70, damping: 12)
    let animation: Animation = .linear
     //   .speed(0.4)
     //   .delay(0.1)
    
    func getOffset() -> CGFloat {
        return (isPresented.wrappedValue ? 0 : UIScreen.main.bounds.height) + max(0, translation.y)
    }
    
    var panelDraggingGesture: some Gesture {
        DragGesture()
            .updating($translation) { current, state, _ in
                state.y = current.translation.height
            }
            .onEnded { state in
                print(state.translation.height)
                if state.translation.height > 100 {
                    self.isPresented.wrappedValue = false
                }
            }
    }
}

extension View {
    func overlaySheet<Content: View>(isPresented: Binding<Bool>,
                                     @ViewBuilder content: @escaping () -> Content) -> some View {
                 self.overlay {
                    GeometryReader { proxy in
                        OverlaySheet(isPresented: isPresented, content: content)
                            .frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
                            .offset(x: 0, y: proxy.size.height - UIScreen.main.bounds.height)
                    }
                }
    }
}
//struct OverlaySheet_Previews: PreviewProvider {
//    static var previews: some View {
//        OverlaySheet()
//    }
//}
